using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// 技能UI管理器
/// 负责技能相关的UI显示和交互
/// </summary>
public class SkillUIManager : MonoBehaviour
{
    [Header("技能面板")]
    [SerializeField] private Transform skillPanel;
    [SerializeField] private GameObject skillSlotPrefab;
    [SerializeField] private SkillDetailUI skillDetailUI;
    
    [Header("技能特效")]
    [SerializeField] private GameObject[] skillEffectPrefabs;
    [SerializeField] private Transform effectParent;
    
    [Header("技能动画设置")]
    [SerializeField] private float skillCastDuration = 1.0f;
    [SerializeField] private float effectDuration = 2.0f;
    
    // 技能UI字典
    private Dictionary<string, SkillSlotUI> skillSlots = new Dictionary<string, SkillSlotUI>();
    
    // 当前选中的技能
    private SkillData selectedSkill;
    private string selectedCharacterId;
    
    private void Start()
    {
        InitializeSkillUI();
    }
    
    /// <summary>
    /// 初始化技能UI
    /// </summary>
    private void InitializeSkillUI()
    {
        // 清空技能面板
        if (skillPanel)
        {
            for (int i = skillPanel.childCount - 1; i >= 0; i--)
            {
                Destroy(skillPanel.GetChild(i).gameObject);
            }
        }
        
        // 隐藏技能详情UI
        if (skillDetailUI)
        {
            skillDetailUI.Hide();
        }
        
        Debug.Log("技能UI初始化完成");
    }
    
    /// <summary>
    /// 更新角色技能列表
    /// </summary>
    public void UpdateCharacterSkills(CharacterData character)
    {
        if (!skillPanel) return;
        
        // 清空现有技能槽位
        foreach (var kvp in skillSlots)
        {
            Destroy(kvp.Value.gameObject);
        }
        skillSlots.Clear();
        
        // 创建技能槽位
        if (character.skills != null)
        {
            foreach (var skill in character.skills)
            {
                GameObject slotObj = Instantiate(skillSlotPrefab, skillPanel);
                SkillSlotUI slotUI = slotObj.GetComponent<SkillSlotUI>();
                
                if (slotUI)
                {
                    slotUI.UpdateSkillData(skill);
                    slotUI.OnSkillClicked += OnSkillClicked;
                    skillSlots[skill.id] = slotUI;
                }
            }
        }
        
        selectedCharacterId = character.id;
    }
    
    /// <summary>
    /// 技能点击事件处理
    /// </summary>
    private void OnSkillClicked(SkillData skill)
    {
        selectedSkill = skill;
        
        // 显示技能详情
        if (skillDetailUI)
        {
            skillDetailUI.ShowSkillDetail(skill);
        }
        
        // 高亮选中的技能槽位
        foreach (var kvp in skillSlots)
        {
            kvp.Value.SetSelected(kvp.Key == skill.id);
        }
        
        Debug.Log($"选中技能: {skill.name}");
    }
    
    /// <summary>
    /// 显示技能特效
    /// </summary>
    public void ShowSkillEffect(string characterId, string skillId, string targetId)
    {
        StartCoroutine(ShowSkillEffectCoroutine(characterId, skillId, targetId));
    }
    
    /// <summary>
    /// 显示技能特效协程
    /// </summary>
    private IEnumerator ShowSkillEffectCoroutine(string characterId, string skillId, string targetId)
    {
        // 获取施法者和目标角色UI
        CharacterUI casterUI = FindCharacterUI(characterId);
        CharacterUI targetUI = FindCharacterUI(targetId);
        
        if (casterUI == null || targetUI == null)
        {
            Debug.LogWarning($"未找到角色UI: 施法者={characterId}, 目标={targetId}");
            yield break;
        }
        
        // 播放施法动画
        yield return StartCoroutine(PlayCastAnimation(casterUI, skillId));
        
        // 创建技能特效
        GameObject effectPrefab = GetSkillEffectPrefab(skillId);
        if (effectPrefab != null)
        {
            yield return StartCoroutine(PlaySkillEffect(effectPrefab, casterUI, targetUI));
        }
        
        // 播放目标受击效果
        yield return StartCoroutine(PlayTargetHitEffect(targetUI, skillId));
    }
    
    /// <summary>
    /// 播放施法动画
    /// </summary>
    private IEnumerator PlayCastAnimation(CharacterUI casterUI, string skillId)
    {
        // 播放施法者动画
        Animator animator = casterUI.GetComponent<Animator>();
        if (animator != null)
        {
            animator.SetTrigger("Cast");
        }
        
        // 等待施法动画
        yield return new WaitForSeconds(skillCastDuration * 0.5f);
        
        // 创建施法特效
        GameObject castEffect = GetCastEffectPrefab(skillId);
        if (castEffect != null)
        {
            GameObject effectObj = Instantiate(castEffect, casterUI.transform.position, Quaternion.identity, effectParent);
            
            // 播放施法音效
            AudioSource audioSource = effectObj.GetComponent<AudioSource>();
            if (audioSource != null)
            {
                audioSource.Play();
            }
            
            yield return new WaitForSeconds(skillCastDuration * 0.5f);
            Destroy(effectObj);
        }
    }
    
    /// <summary>
    /// 播放技能特效
    /// </summary>
    private IEnumerator PlaySkillEffect(GameObject effectPrefab, CharacterUI casterUI, CharacterUI targetUI)
    {
        // 创建特效对象
        GameObject effectObj = Instantiate(effectPrefab, effectParent);
        
        // 设置特效位置和移动
        Vector3 startPos = casterUI.transform.position;
        Vector3 endPos = targetUI.transform.position;
        
        effectObj.transform.position = startPos;
        
        // 移动特效到目标
        float timer = 0;
        while (timer < skillCastDuration)
        {
            timer += Time.deltaTime;
            float progress = timer / skillCastDuration;
            effectObj.transform.position = Vector3.Lerp(startPos, endPos, progress);
            yield return null;
        }
        
        // 在目标位置播放爆炸效果
        PlayExplosionEffect(endPos);
        
        // 销毁特效对象
        Destroy(effectObj);
    }
    
    /// <summary>
    /// 播放目标受击效果
    /// </summary>
    private IEnumerator PlayTargetHitEffect(CharacterUI targetUI, string skillId)
    {
        // 播放受击动画
        Animator animator = targetUI.GetComponent<Animator>();
        if (animator != null)
        {
            animator.SetTrigger("Hit");
        }
        
        // 震动效果
        StartCoroutine(PlayShakeEffect(targetUI.transform));
        
        // 颜色闪烁效果
        StartCoroutine(PlayHitColorEffect(targetUI));
        
        yield return new WaitForSeconds(0.5f);
    }
    
    /// <summary>
    /// 播放震动效果
    /// </summary>
    private IEnumerator PlayShakeEffect(Transform target)
    {
        Vector3 originalPosition = target.position;
        float shakeDuration = 0.3f;
        float shakeIntensity = 0.1f;
        
        float timer = 0;
        while (timer < shakeDuration)
        {
            timer += Time.deltaTime;
            
            Vector3 randomOffset = Random.insideUnitSphere * shakeIntensity;
            target.position = originalPosition + randomOffset;
            
            yield return null;
        }
        
        target.position = originalPosition;
    }
    
    /// <summary>
    /// 播放受击颜色效果
    /// </summary>
    private IEnumerator PlayHitColorEffect(CharacterUI targetUI)
    {
        Color originalColor = targetUI.GetCharacterColor();
        Color hitColor = Color.red;
        
        float timer = 0;
        float flashDuration = 0.2f;
        bool isRed = true;
        
        while (timer < flashDuration)
        {
            timer += Time.deltaTime;
            isRed = !isRed;
            targetUI.SetCharacterColor(isRed ? hitColor : originalColor);
            yield return new WaitForSeconds(0.05f);
        }
        
        targetUI.SetCharacterColor(originalColor);
    }
    
    /// <summary>
    /// 播放爆炸效果
    /// </summary>
    private void PlayExplosionEffect(Vector3 position)
    {
        // 创建爆炸特效
        GameObject explosionPrefab = GetExplosionEffectPrefab();
        if (explosionPrefab != null)
        {
            GameObject explosionObj = Instantiate(explosionPrefab, position, Quaternion.identity, effectParent);
            
            // 播放爆炸音效
            AudioSource audioSource = explosionObj.GetComponent<AudioSource>();
            if (audioSource != null)
            {
                audioSource.Play();
            }
            
            // 自动销毁
            Destroy(explosionObj, effectDuration);
        }
    }
    
    /// <summary>
    /// 根据技能ID获取特效预制体
    /// </summary>
    private GameObject GetSkillEffectPrefab(string skillId)
    {
        // 这里可以根据技能ID返回对应的特效预制体
        // 暂时返回第一个特效作为示例
        if (skillEffectPrefabs != null && skillEffectPrefabs.Length > 0)
        {
            int index = Mathf.Abs(skillId.GetHashCode()) % skillEffectPrefabs.Length;
            return skillEffectPrefabs[index];
        }
        return null;
    }
    
    /// <summary>
    /// 根据技能ID获取施法特效预制体
    /// </summary>
    private GameObject GetCastEffectPrefab(string skillId)
    {
        // 这里可以根据技能ID返回对应的施法特效预制体
        // 暂时返回第一个特效作为示例
        if (skillEffectPrefabs != null && skillEffectPrefabs.Length > 0)
        {
            int index = Mathf.Abs(skillId.GetHashCode()) % skillEffectPrefabs.Length;
            return skillEffectPrefabs[index];
        }
        return null;
    }
    
    /// <summary>
    /// 获取爆炸特效预制体
    /// </summary>
    private GameObject GetExplosionEffectPrefab()
    {
        // 这里可以返回爆炸特效预制体
        // 暂时返回第一个特效作为示例
        if (skillEffectPrefabs != null && skillEffectPrefabs.Length > 0)
        {
            return skillEffectPrefabs[0];
        }
        return null;
    }
    
    /// <summary>
    /// 查找角色UI
    /// </summary>
    private CharacterUI FindCharacterUI(string characterId)
    {
        CharacterUI[] allCharacterUIs = FindObjectsOfType<CharacterUI>();
        foreach (var characterUI in allCharacterUIs)
        {
            if (characterUI.CharacterId == characterId)
            {
                return characterUI;
            }
        }
        return null;
    }
    
    /// <summary>
    /// 使用技能
    /// </summary>
    public void UseSkill(string skillId, string targetId)
    {
        if (string.IsNullOrEmpty(selectedCharacterId))
        {
            Debug.LogWarning("未选择角色");
            return;
        }
        
        // 通知Lua系统使用技能
        var luaBattleManager = FindObjectOfType<LuaBattleManager>();
        if (luaBattleManager != null)
        {
            // 这里需要调用Lua系统的技能使用接口
            Debug.Log($"使用技能: {skillId}, 目标: {targetId}");
        }
    }
    
    /// <summary>
    /// 取消技能选择
    /// </summary>
    public void CancelSkillSelection()
    {
        selectedSkill = null;
        
        // 取消所有技能槽位的高亮
        foreach (var kvp in skillSlots)
        {
            kvp.Value.SetSelected(false);
        }
        
        // 隐藏技能详情UI
        if (skillDetailUI)
        {
            skillDetailUI.Hide();
        }
    }
}

/// <summary>
/// 技能槽位UI组件
/// </summary>
public class SkillSlotUI : MonoBehaviour
{
    [Header("技能信息")]
    [SerializeField] private Image skillIcon;
    [SerializeField] private TextMeshProUGUI skillName;
    [SerializeField] private TextMeshProUGUI cooldownText;
    [SerializeField] private TextMeshProUGUI costText;
    [SerializeField] private Button skillButton;
    [SerializeField] private Image cooldownOverlay;
    [SerializeField] private Image selectedBorder;
    
    private SkillData currentSkill;
    
    // 事件委托
    public System.Action<SkillData> OnSkillClicked;
    
    private void Start()
    {
        if (skillButton != null)
        {
            skillButton.onClick.AddListener(OnSkillButtonClicked);
        }
    }
    
    /// <summary>
    /// 更新技能数据
    /// </summary>
    public void UpdateSkillData(SkillData skill)
    {
        currentSkill = skill;
        
        // 更新技能信息
        if (skillName) skillName.text = skill.name;
        if (costText) costText.text = skill.costMp.ToString();
        
        // 更新冷却时间
        UpdateCooldown(skill.currentCooldown);
        
        // 更新可用状态
        UpdateUsableState(skill.isUsable);
        
        // 这里可以根据技能ID设置技能图标
        // if (skillIcon) skillIcon.sprite = GetSkillIcon(skill.id);
    }
    
    /// <summary>
    /// 更新冷却时间
    /// </summary>
    public void UpdateCooldown(int currentCooldown)
    {
        if (cooldownText) cooldownText.text = currentCooldown > 0 ? currentCooldown.ToString() : "";
        
        if (cooldownOverlay)
        {
            cooldownOverlay.fillAmount = currentSkill != null ? (float)currentCooldown / currentSkill.maxCooldown : 0;
            cooldownOverlay.gameObject.SetActive(currentCooldown > 0);
        }
    }
    
    /// <summary>
    /// 更新可用状态
    /// </summary>
    public void UpdateUsableState(bool isUsable)
    {
        if (skillButton)
        {
            skillButton.interactable = isUsable;
        }
        
        // 设置不可用状态的视觉效果
        if (skillIcon)
        {
            Color iconColor = skillIcon.color;
            iconColor.a = isUsable ? 1.0f : 0.5f;
            skillIcon.color = iconColor;
        }
    }
    
    /// <summary>
    /// 设置选中状态
    /// </summary>
    public void SetSelected(bool isSelected)
    {
        if (selectedBorder)
        {
            selectedBorder.gameObject.SetActive(isSelected);
        }
    }
    
    /// <summary>
    /// 技能按钮点击事件
    /// </summary>
    private void OnSkillButtonClicked()
    {
        if (currentSkill != null && OnSkillClicked != null)
        {
            OnSkillClicked(currentSkill);
        }
    }
}

/// <summary>
/// 技能详情UI组件
/// </summary>
public class SkillDetailUI : MonoBehaviour
{
    [Header("技能详情")]
    [SerializeField] private Image skillIcon;
    [SerializeField] private TextMeshProUGUI skillName;
    [SerializeField] private TextMeshProUGUI skillDescription;
    [SerializeField] private TextMeshProUGUI skillCost;
    [SerializeField] private TextMeshProUGUI skillCooldown;
    [SerializeField] private TextMeshProUGUI skillRange;
    [SerializeField] private TextMeshProUGUI skillDamage;
    [SerializeField] private Button useButton;
    [SerializeField] private Button cancelButton;
    
    private SkillData currentSkill;
    private string currentCharacterId;
    
    // 事件委托
    public System.Action<string, string> OnUseSkill;
    public System.Action OnCancel;
    
    private void Start()
    {
        if (useButton) useButton.onClick.AddListener(OnUseButtonClicked);
        if (cancelButton) cancelButton.onClick.AddListener(OnCancelButtonClicked);
        
        Hide();
    }
    
    /// <summary>
    /// 显示技能详情
    /// </summary>
    public void ShowSkillDetail(SkillData skill, string characterId = null)
    {
        currentSkill = skill;
        currentCharacterId = characterId;
        
        // 更新技能信息
        if (skillName) skillName.text = skill.name;
        if (skillCost) skillCost.text = $"消耗: {skill.costMp} MP";
        if (skillCooldown) skillCooldown.text = $"冷却: {skill.maxCooldown} 回合";
        
        // 这里可以设置技能图标和详细描述
        // if (skillIcon) skillIcon.sprite = GetSkillIcon(skill.id);
        // if (skillDescription) skillDescription.text = GetSkillDescription(skill.id);
        
        // 更新使用按钮状态
        if (useButton)
        {
            useButton.interactable = skill.isUsable;
        }
        
        gameObject.SetActive(true);
    }
    
    /// <summary>
    /// 隐藏技能详情
    /// </summary>
    public void Hide()
    {
        gameObject.SetActive(false);
        currentSkill = null;
        currentCharacterId = null;
    }
    
    /// <summary>
    /// 使用按钮点击事件
    /// </summary>
    private void OnUseButtonClicked()
    {
        if (currentSkill != null && OnUseSkill != null)
        {
            OnUseSkill(currentSkill.id, currentCharacterId);
        }
    }
    
    /// <summary>
    /// 取消按钮点击事件
    /// </summary>
    private void OnCancelButtonClicked()
    {
        if (OnCancel != null)
        {
            OnCancel();
        }
    }
}